<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="-mb-17px">
      <el-form-item label="文件名称" prop="name">
        <el-input
          v-model="queryParams.name"
          class="!w-240px"
          placeholder="请输入文件名称"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="年份" prop="year">
        <el-date-picker
          v-model="queryParams.year"
          type="year"
          value-format="YYYY"
          class="!w-240px"
          @change="handleQuery"
          placeholder="请选择年份"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
        <el-button type="primary" plain v-if="userRoleId === 1" @click="openAddDialog">
          <Icon class="mr-5px" icon="ep:plus" />
          新增
        </el-button>
        <el-button type="danger" plain v-if="userRoleId === 1" @click="allDelBtn">
          <Icon class="mr-5px" icon="ep:delete" />
          批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
  <!-- 列表 -->
  <ContentWrap>
    <el-table
      :data="list"
      v-loading="loading"
      empty-text="暂无记录"
      element-loading-text="Loading..."
      stripe
      :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
      show-overflow-tooltip
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" v-if="userRoleId === 1" width="50" />
      <el-table-column align="center" label="文件名称" prop="name" width="260" />
      <el-table-column align="center" label="年份" prop="year" min-width="120" />
      <el-table-column align="center" label="来源" prop="source" min-width="120" />
      <el-table-column align="center" label="发文部门" prop="deptId" min-width="120" />
      <el-table-column align="center" label="操作" fixed="right" width="160">
        <template #default="scope">
          <el-button link type="primary" @click="downloadFile(scope.row)">下载</el-button>
          <el-button link type="primary" @click="previewFile(scope.row)">预览</el-button>
          <el-button link type="primary" v-if="userRoleId === 1" @click="delBtn(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      class="mt-35px text-14px"
      v-model:current-page="queryParams.pageNo"
      v-model:page-size="queryParams.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      background
      :hide-on-single-page="value"
      layout="total,sizes,prev, pager, next,jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <el-dialog
      :title="filePreviewName"
      v-model="isPreviewOpen"
      :style="{ height: '100vh', margin: '0 auto', padding: 0 }"
      width="70%"
    >
      <iframe v-if="pdfUrl" :src="pdfUrl" style="width: 100%; height: 85vh"></iframe>
    </el-dialog>
  </ContentWrap>
  <AddDialog ref="addFile" @success="getList" />
</template>

<script lang="ts" setup>
import * as KmsApi from '@/api/project/kms'
import * as IctApi from '@/api/project/ict'
import { ref, reactive, onMounted } from 'vue'
import { getUserProfile } from '@/api/system/user/profile'
import AddDialog from './components/addDialog.vue'

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const selectList = ref([]) // 表格选中数据
const value = ref(true)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: '',
  year: ''
})

const addFile = ref()

const queryFormRef = ref()

//获取用户角色id
const userRoleId = ref()
const getUser = async () => {
  await getUserProfile().then((res) => {
    userRoleId.value = res.roles[0].id
  })
}

// 控制预览文件模态框展示
const isPreviewOpen = ref(false)
const pdfUrl = ref('')
const filePreviewName = ref('')

// 条数变化
const handleSizeChange = (e) => {
  queryParams.pageSize = e
  queryParams.pageNo = 1
  getList()
}

// 页码变化
const handleCurrentChange = (e) => {
  queryParams.pageNo = e
  getList()
}

// 查询列表
const getList = async () => {
  IctApi.getFilePage(queryParams)
    .then((res) => {
      list.value = res.list || []
      total.value = res.total || 0
      if (list.value.length === 0) {
        value.value = true
      } else {
        value.value = false
      }
      loading.value = false
    })
    .catch(() => {
      loading.value = false
    })
}

// 搜索按钮操作
const handleQuery = async () => {
  queryParams.pageNo = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.pageNo = 1
  getList()
}

// 下载附件
const downloadFile = (file) => {
  const params = {
    doc_id: file.fileId,
    is_preview: false
  }
  KmsApi.previewAndDownloadFile(params).then((res) => {
    const downloadFileName = file.name
    const blobData = new Blob([res])
    const fileUrl = URL.createObjectURL(blobData)
    const link = document.createElement('a')
    link.href = fileUrl
    link.setAttribute('download', downloadFileName)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(fileUrl)
  })
}

// 预览附件
const previewFile = (file) => {
  const params = {
    doc_id: file.fileId,
    is_preview: true
  }
  KmsApi.previewAndDownloadFile(params).then((res) => {
    filePreviewName.value = file.name
    const blobPDF = new Blob([res], { type: 'application/pdf' })
    pdfUrl.value = '/pdfjs/web/viewer.html?file=' + window.URL.createObjectURL(blobPDF)
    isPreviewOpen.value = true
  })
}

// 新增附件
const openAddDialog = () => {
  addFile.value.open()
}

// 批量删除
const handleSelectionChange = (e) => {
  selectList.value = e
}
const allDelBtn = () => {
  if (selectList.value.length == 0) {
    ElMessage({
      message: '至少选中一条数据！',
      type: 'warning'
    })
    return
  }
  ElMessageBox.confirm(`确认删除选中制度文件吗？删除当前选中数据无法恢复，请谨慎操作！`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      const idList = reactive([])
      selectList.value.forEach((item) => {
        idList.push(item.id)
      })
      IctApi.deleteFileList(idList).then((res) => {
        if (res === true) {
          ElMessage.success('删除成功！')
          getList()
        }
      })
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 删除
const delBtn = (row: any) => {
  ElMessageBox.confirm(
    `确认删除制度文件【${row.name}】吗？删除当前数据无法恢复，请谨慎操作！`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      // await KmsApi.deleteFile(row.doc_id)
      IctApi.deleteFileList([row.id]).then((res) => {
        if (res === true) {
          ElMessage.success('删除成功！')
          getList()
        }
      })
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 初始化
onMounted(() => {
  getList()
  getUser()
})
</script>
<style scoped>
.el-pagination {
  justify-content: flex-end;
}
</style>